package system.register.impl;

import system.register.ClientInterface;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created by 陈文杰 on 2022/4/12 19:13
 */

/*
1.发送用户数据给服务端
2.接收服务端发送的数据
3.依据服务端回传的数据决定业务逻辑
 */
public class ClientImpl implements ClientInterface {
    private static Socket socket = null;
    private String administratorName = null;
    private int token = 1;

    public String getAdministratorName() {
        return administratorName;
    }

    @Override
    //登录方法
    public void register() {
        Scanner scanner = new Scanner(System.in);
        String name = null, password = null;//记录用户信息

        //调用一个Socket对象,访问8888端口
        try {
            socket = new Socket(InetAddress.getLocalHost(), 8888);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //获取和socket相关的输出流对象
        OutputStream outputStream = null;
        try {
            outputStream = socket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //用户输入用户名和密码,传向服务端验证
        try {
            System.out.print("请输入用户名:");
            name = scanner.next();
            System.out.print("请输入密码:");
            password = scanner.next();
            System.out.println();
            administratorName = name;
            outputStream.write((name + "/" + password).getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }

        //向服务端发送消息结束信息
        try {
            socket.shutdownOutput();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    @Override
    //接收服务端发送的消息
    public String receive() {
        String isTrue = null;//用于保存数据

        //创建和socket相关的输入流对象
        InputStream inputStream = null;
        try {
            inputStream = socket.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //读取从服务端接收到的信息
        byte[] bytes = new byte[1024];
        int readLines = 0;
        while (true) {
            try {
                readLines=inputStream.read(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (readLines==-1){
                break;
            }
            isTrue = new String(bytes, 0, readLines);
        }


        if (isTrue.equals("管理员") ) {
            return "管理员";
        }
        if (isTrue.equals("收银员") ) {
            return "收银员";
        }

        return "查无此人";
    }
}
